import {createStore} from "redux"

import reducer from "./reducer"


// store.dispatch = function(action){
//     console.log(store.getState())
//     dispatch(action)
//     console.log(store.getState())
// }

// 中间件基本功能 获取状态，派发动作 执行下一个中间件
let logger = function ({dispatch, getState}) {
    return function (next) {
        return function (action) {
            console.log("old state", store.getState())
            next(action)
            console.log("new state", store.getState())
        }
    }
}

let applyMiddleWare = function (middleWare) {
    return function (createStore) {
        return function (reducer) {
            let store = createStore(reducer);
            let dispatch;
            let middlewareAPI = {
                getState: store.getState,
                dispatch: action => dispatch(action)
            }
            middleWare = middleWare(middlewareAPI);
             dispatch = middleWare(store.dispatch);
            return {...store, dispatch};
        }
    }
}

// let store = createStore(reducer)

let store = applyMiddleWare(logger)(createStore)(reducer)

window.$store = store;

export default store;

